package com.cincc.cinccimdemo.viewmodel;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.cincc.im.core.IMSipPhoneCtrl;
import com.cincc.im.model.dbmodel.ConversationInfo;
import com.cincc.im.util.ImManager;

import java.util.List;

public class ConversationListViewModel extends ViewModel {
    private MutableLiveData<List<ConversationInfo>> conversationListLiveData;

    public MutableLiveData<List<ConversationInfo>> conversationListLiveData() {
        if (conversationListLiveData == null) {
            conversationListLiveData = new MutableLiveData<>();
        }
        ImManager.getInstance().getWorkHandler().post(() -> {
            List<ConversationInfo> conversationInfos = IMSipPhoneCtrl.getInstance().getConversationList();
            conversationListLiveData.postValue(conversationInfos);
        });
        return conversationListLiveData;
    }


    public void reloadConversationList() {
        if (conversationListLiveData == null) {
            return;
        }
        ImManager.getInstance().getWorkHandler().post(() -> {
            List<ConversationInfo> conversationInfos = IMSipPhoneCtrl.getInstance().getConversationList();
            conversationListLiveData.postValue(conversationInfos);
        });
    }


    private MutableLiveData<Integer> unreadCountLiveData;

    public MutableLiveData<Integer> unreadCountLiveData(List<ConversationInfo> list) {
        if (unreadCountLiveData == null) {
            unreadCountLiveData = new MutableLiveData<>();
        }

        reloadConversationUnreadStatus(list);
        return unreadCountLiveData;
    }

    public void reloadConversationUnreadStatus(List<ConversationInfo> list) {
        int count = list.stream().filter(item -> !item.noDisturb).mapToInt(item -> item.unreadNum).sum();
        postUnreadCount(count);
    }

    private void postUnreadCount(Integer unreadCount) {
        if (unreadCountLiveData == null) {
            return;
        }
        unreadCountLiveData.postValue(unreadCount);
    }
}
